<template>
  <div class="comment-section">
    <!-- 评分统计 -->
    <el-card class="statistics-card">
      <div class="rating-overview">
        <div class="rating-left">
          <div class="average-score">{{ averageRating }}</div>
          <div class="score-text">综合评分</div>
          <el-rate
              v-model="averageRating"
              disabled
              :allow-half="true"
              class="score-stars"
          />
        </div>
        <div class="rating-right">
          <div class="total-comments">
            <span class="number">{{ totalComments }}</span>
            <span class="text">用户评价</span>
          </div>
          <div class="like-count">
            <span class="number">{{ totalLikes }}</span>
            <span class="text">获赞数</span>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 评论输入 -->
    <el-card class="comment-input-card">
      <div class="input-header">
        <span>评分：</span>
        <el-rate v-model="newComment.rating" />
      </div>
      <el-input
          v-model="newComment.content"
          type="textarea"
          :rows="3"
          placeholder="请分享您的使用体验..."
      />
      <div class="input-footer">
        <el-button type="primary" @click="submitComment">发表评论</el-button>
      </div>
    </el-card>

    <!-- 评论列表 -->
    <div class="comment-list">
      <el-card v-for="item in commentList" :key="item.id" class="comment-item">
        <div class="comment-header">
          <div class="user-info">
            <el-avatar :size="40" :src="item.avatar" />
            <span class="username">{{ item.username || '匿名用户' }}</span>
          </div>
          <el-rate v-model="item.rating" disabled />
        </div>

        <div class="comment-body">
          <p class="comment-text">{{ item.content }}</p>
          <div class="comment-meta">
            <span class="time">{{ formatTime(item.create_time) }}</span>
            <div class="actions">
              <el-button
                  type="primary"
                  link
                  @click="handleLike(item)"
              >
                <el-icon><StarFilled /></el-icon>
                {{ item.like_count }}
              </el-button>
            </div>
          </div>
        </div>

        <!-- 商家回复 -->
        <div v-if="item.answer" class="reply-section">
          <div class="reply-header">
            <el-tag size="small" type="success">商家回复</el-tag>
          </div>
          <p class="reply-content">{{ item.answer }}</p>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="totalComments"
          layout="prev, pager, next"
          @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { get, post } from '@/net'
import {StarFilled} from "@element-plus/icons-vue"
import { useRoute } from 'vue-router'
import dayjs from 'dayjs'

const route = useRoute()
const currentPage = ref(1)
const pageSize = ref(4)
const commentList = ref([])
const allCommentList = ref([])
const totalComments = ref(0)
const userInfo = ref({})
// 新评论
const newComment = ref({
  rating: 5,
  content: ''
})

// 计算平均评分
const averageRating = computed(() => {
  if (!allCommentList.value.length) return 0
  const total = allCommentList.value.reduce((sum, item) => sum + item.rating, 0)
  return (total / allCommentList.value.length).toFixed(1)
})

// 计算总点赞数
const totalLikes = computed(() => {
  return allCommentList.value.reduce((sum, item) => sum + item.like_count, 0)
})

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 获取评论列表
const getComments = async () => {
  const teamId = route.params.id
  get(`/api/comment/getCommentListByTeamId/${currentPage.value}/${teamId}`, (res) => {
    commentList.value = res.list
    totalComments.value = res.total
    // console.log(commentList.value)
  }, (err) => {
    ElMessage.warning("获取评论失败")
    console.log(err)
  })

}


const getAllComments = async () => {
  const teamId = route.params.id
  get(`/api/comment/getAllCommentByTeamId/${teamId}`, (res) => {
    allCommentList.value = res
    // console.log(allCommentList.value)
  }, (err) => {
    ElMessage.warning("获取评论失败")
    console.log(err)
  })
}



// 提交评论
const submitComment = async () => {
  if (!newComment.value.content.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  userInfo.value =  JSON.parse(window.localStorage.getItem('user'))

  const data = {
    team_id: route.params.id,  // 从路由获取团队id
    content: newComment.value.content,
    rating: newComment.value.rating,
    user_id: userInfo.value.id,// 从本地存储获取用户id
    status: 0,
    like_count: 0
  }

  post('/api/comment/addComment', data, () => {
    ElMessage.success('评论成功')
    // 重置表单
    newComment.value.content = ''
    newComment.value.rating = 5
    // 刷新评论列表
    getComments()
  }, (err) => {
    ElMessage.warning('评论失败')
    console.log(err)
  })
}

// 点赞
const handleLike = (comment) => {
  post(`/api/comment/like/${comment.id}`, null, () => {
    comment.like_count++ // 本地更新点赞数
    getAllComments()
    ElMessage.success('点赞成功')
  }, (err) => {
    ElMessage.warning('点赞失败')
    console.log(err)
  })
}

// 分页
const handlePageChange = (page) => {
  currentPage.value = page
  getComments()
}

onMounted(() => {
  getComments()
  getAllComments()
})
</script>

<style scoped>
.comment-section {
  padding: 20px 0;
}

.statistics-card {
  margin-bottom: 20px;
}

.rating-overview {
  display: flex;
  align-items: center;
  padding: 20px;
}

.rating-left {
  text-align: center;
  padding-right: 40px;
  border-right: 1px solid #eee;
}

.average-score {
  font-size: 36px;
  color: #409EFF;
  font-weight: bold;
}

.score-text {
  color: #666;
  margin: 8px 0;
}

.rating-right {
  flex: 1;
  display: flex;
  justify-content: space-around;
  text-align: center;
}

.number {
  font-size: 24px;
  color: #409EFF;
  font-weight: bold;
  display: block;
}

.text {
  color: #666;
  margin-top: 4px;
}

.comment-input-card {
  margin-bottom: 20px;
}

.input-header {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.input-footer {
  margin-top: 15px;
  text-align: right;
}

.comment-item {
  margin-bottom: 15px;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.comment-text {
  margin: 0;
  line-height: 1.6;
}

.comment-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  color: #999;
}

.reply-section {
  margin-top: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
}

.reply-header {
  margin-bottom: 8px;
}

.reply-content {
  margin: 0;
  color: #666;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>